<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑区域 -->
      <SubBread />
      <!-- 筛选条件区域 -->
      <SubFilter />
      <!-- 筛选结果区域 -->
      <div class="goods-list">
        <!-- 列表筛选条件 -->
        <SubSort />
        <!-- 筛选列表 -->
        <SubList />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, provide } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'
import { findSubCategoryFilter } from '@/api/category'
import SubFilter from './components/sub-filter.vue'
import SubBread from './components/sub-bread.vue'
import SubSort from './components/sub-sort.vue'
import SubList from './components/sub-list.vue'

export default {
  name: 'SubCategory',
  components: {
    SubBread,
    SubFilter,
    SubSort,
    SubList
  },
  setup () {
    const subCategoryData = ref({})
    const route = useRoute()
    // 提供二级类目数据
    provide('subCategoryData', subCategoryData)

    // 筛选条件数据
    const filterParams = ref({
      attrs: [], // 一般商品属性 => {groupName: "规格", propertyName: "CPE加厚手套-100只/盒"}
      sortField: null, // 排序 => // publishTime(最新), orderNum(人气), price(价格), evaluateNum(评论)
      brandId: null // 品牌ID => '1'
    })
    // 提供过滤条件数据
    provide('filterParams', filterParams)

    async function loadSubData (id) {
      const res = await findSubCategoryFilter(id)
      console.log('二级类目：', res)
      // 品牌和商品规格选项 =》  我们自己添加一个全部的分类
      // 品牌选中属性添加
      res.result.brands.forEach(item => {
        item.selected = false
      })
      // 默认全部选中
      res.result.brands.unshift({
        name: '全部',
        id: null,
        selected: true
      })
      res.result.saleProperties.forEach((item) => {
        // 给每一个规格添加一个专门用来控制是否激活的字段 selected true 激活 false 不激活
        item.properties.forEach(item => {
          item.selected = false
        })
        // 默认全部选中
        item.properties.unshift({
          name: '全部',
          id: null,
          selected: true
        })
      })
      subCategoryData.value = res.result
      // 提供二级类目数据 => 注意：不能在这里提供=》请求延迟
      // provide('subCategoryData', subCategoryData)
    }
    onMounted(() => {
      loadSubData(route.params.id)
    })

    onBeforeRouteUpdate((to) => {
      loadSubData(to.params.id)
    })

    // return { subCategoryData }
  }
}
</script>
<style scoped lang='less'>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
}
</style>
